const uuid = require('uuid')
const models = require('../models')
const utils = require('../utils')

exports.setLoginSession = async (ctx, userId) => {
  const now = utils.idate()
  const token = uuid.v4()

  ctx.session.loginId = userId
  ctx.session.loginAt = now
  ctx.session.token = token

  await models.token.create({
    userId: userId,
    token: token,
    expireAt: now.nextOf('date', 30), // 30 天
    createdAt: now
  })

  return token
}

exports.validateToken = async (token) => {
  const tokenInfo = await models.token.getValidToken(token)

  if (!tokenInfo) return [false, null]

  return [true, tokenInfo.userId]
}
